<template>
	<view class="gz-search">
		<view class="main">
			<image src="/static/indexImg/list-search.svg" alt=""></image><!--放大镜-->

			<input type="text" v-model="vdata.searchValue" :placeholder="placeholder" :auto-blur="true" @input="changeHandle($event)" placeholder-style="color:#999;fontSize:26rpx" style="font-size: 26rpx;color:#000">

			<!-- 清空图片 -->
			<image @click="clearText" src="@/static/indexImg/del.svg" class="clear-img" v-if="vdata.isDel"></image>
		</view>

		<slot>
			<view class="btn-text" v-if="vdata.isDel && !vdata.searched" @click="searchHandle">搜索</view>
			<view class="btn-text" v-else @click="cancelHandle">取消</view>
		</slot>

	</view>
</template>

<script setup>
	import { ref, nextTick, reactive } from 'vue'

	const props = defineProps({
		placeholder: { type: String, default: '搜索' },
	})

	const emits = defineEmits(['searchHandle', 'cancelHandle', 'changeHandle', 'clearText'])

	const vdata = reactive({
		searchValue: '', // 搜索内容
		isDel: false, // 清空按钮是否展示
		searched: false, // 是否已经进行过搜索
	})

	// 当输入内容时
	const changeHandle = e => {
		vdata.searched = false // 当再次输入内容后，进入未搜状态
		vdata.isDel = true // 打开清空按钮
		vdata.searchValue = e.detail.value // 为搜索内容赋值
		emits('changeHandle', vdata.searchValue)
	}

	// 点击清除按钮
	const clearText = () => {
		vdata.isDel = false
		vdata.searchValue = ''
		emits('clearText')
	}

	// 发起搜索
	const searchHandle = () => {
		vdata.searched = true // 进入搜索状态
		emits('searchHandle', vdata.searchValue)
	}

	// 点击取消 页面回退
	const cancelHandle = () => emits('cancelHandle')

	// 获取搜索框中的内容
	const getValue = () => vdata.searchValue

	defineExpose({ clearText, getValue })
</script>

<style scoped lang="scss">
	.gz-search {
		display: flex;
		padding: 16rpx 30rpx 30rpx;
		box-sizing: border-box;
		align-items: center;
		position: relative;

		&::after {
			content: '';
			position: absolute;
			bottom: 0;
			left: 0;
			height: 1rpx;
			width: 100%;
			background-color: #D9D9D9;
			transform: scaleY(0.6);
		}

		.main {
			flex-grow: 1;
			height: 100%;
			display: flex;
			align-items: center;
			padding-left: 20rpx;
			height: 72rpx;
			box-sizing: border-box;
			background-color: #fff;
			border-radius: 12rpx;
			background: #f2f2f2;
		}

		image {
			width: 24rpx;
			height: 24rpx;
			margin-right: 20rpx;
		}

		input {
			flex-grow: 1;
			margin-right: 20rpx;
		}

		.btn-text {
			font-size: 28rpx;
			color: #12B362;
			margin-left: 30rpx;
		}

		.clear-img {
			width: 32rpx;
			height: 32rpx;
		}
	}

	.search-text {
		color: $uni-color-primary;
	}
</style>